package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.dao.DepartmentsDao;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Transactional(rollbackFor = Exception.class)
public class UserController {
    @Autowired
    UserDao userDao;
    @Autowired
    DepartmentsDao department;
    private User user = null;
    private ModelAndView mv = new ModelAndView();

    @GetMapping("/gologin")
    public ModelAndView login() {
        mv.setViewName("login");
        return mv;
    }

    @GetMapping("/goregister")
    public ModelAndView register() {
        mv.setViewName("register");
        return mv;
    }

    @RequestMapping(value = "/login")
    public String login(@RequestParam(name = "username") String username, @RequestParam(name = "password") String password) throws IOException {
        user = userDao.findByAccounts_NameAndAccounts_Pwd(username, password);
        if (user != null) {
            return  "ok";
        } else {
            return "error";
        }
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView register(Register register, @RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        ModelAndView mv = new ModelAndView("redirect:/gologin");
        user = userDao.findByAccounts_Name(register.getUname());
        if (user==null && register.getUpwd1().equals(register.getUpwd2())) {
            String fileName = file.getOriginalFilename();
            String finalPath = null;
            if (!file.isEmpty()) {
                byte[] bytes = file.getBytes();
                String path = "F:\\springboot\\demo\\src\\main\\resources\\static\\files";
                File location = new File(path);
                if (!location.exists()) {
                    location.mkdir();
//                    创建新目录
                }
                BufferedOutputStream bufferedOutputStream = new
                        BufferedOutputStream(new FileOutputStream(new File(path + "\\" + fileName)));
                bufferedOutputStream.write(bytes);
                bufferedOutputStream.close();
                finalPath = "/files/" + fileName;
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = df.format(new Date());
            Accounts accounts = new Accounts();
            accounts.setName(register.getUname());
            accounts.setPwd(register.getUpwd1());
            User user = new User();
            user.setAccounts(accounts);
            user.setName(register.getName());
            user.setAge(register.getAge());
            user.setGender(register.getSex());
            user.setCreateTime(format);
            user.setUrl(finalPath);
            userDao.saveAndFlush(user);
        } else {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('注册失败!')</script>");
            mv.setViewName("register");
        }

        return mv;
}

    @RequestMapping(value = "/register1", method = RequestMethod.POST)
    public String register(Register register) throws IOException {
        if (!register.getUpwd1().equals(register.getUpwd2())) {
            return "repetition";
        } else {
            return "ok";
        }
    }

    @RequestMapping(value = "/register2", method = RequestMethod.POST)
    public void register(@RequestParam("uname") String uname, HttpServletResponse response) throws IOException {
        user = userDao.findByAccounts_Name(uname);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if (uname == null) {
            out.print("error");
        } else {
            if (user != null) {
                out.print("index");
            } else {
                out.print("ok");
            }
        }
    }

    //登录主页
    @GetMapping("/index")
    public ModelAndView index() {
        mv.addObject("user", user);
        mv.setViewName("index");
        return mv;
    }

    //退出
    @RequestMapping("/loginout")
    public ModelAndView loginout(HttpSession session){
        session.invalidate();
        mv.setViewName("redirect:gologin");
        return mv;
    }

    //跳转用户管理
    @RequestMapping("/usermag")
    public ModelAndView usermag(ModelAndView mv){
        mv.addObject("user",user);
        mv.setViewName("table-font-list");
        return mv;
    }

    //json数据
    @RequestMapping("/select")
    public JSONObject select(@RequestParam("page") int page,@RequestParam("limit") int limit){
        Pageable pageable = PageRequest.of(page-1,limit);
        Page<User> p = userDao.findAll(pageable);
        JSONObject object = new JSONObject();
        object.put("code",0);
        object.put("msg","获取数据成功");
        object.put("data",p.getContent());
        object.put("count",p.getTotalElements());
        return object;
    }

    //删除用户
    @RequestMapping("/del")
    public void deleteById(@RequestParam("id")int id, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(id>0) {
            userDao.deleteById(id);
            out.print("ok");
        }else {
            out.print("error");
        }
    }

    //查看用户
    @RequestMapping("/selectById1/{id}")
    public ModelAndView selectById1(@PathVariable("id")int id){
        User user = userDao.findById(id);
        ModelAndView mv = new ModelAndView("userInfo");
        mv.addObject("userInfo",user);
        return mv;
    }

    //修改用户(先查看)
    @RequestMapping("/selectById2/{id}")
    public ModelAndView selectById2(@PathVariable("id")int id){
        User user = userDao.findById(id);
        List<Departments> list = department.findAll();
        ModelAndView mv = new ModelAndView("userlist");
        mv.addObject("userInfo",user);
        mv.addObject("departments",list);
        return mv;
    }

    //修改用户
    @RequestMapping("/update")
    public String update(Update user,@RequestParam("file") MultipartFile file){
        Departments department1 = new Departments();
        List<Departments> list = department.findAll();
        switch (user.getDepartment()){
            case "1":department1 = list.get(0);break;
            case "2":department1 = list.get(1);break;
            case "3":department1 = list.get(2);break;
            case "4":department1 = list.get(3);break;
            case "5":department1 = list.get(4);break;
        }
        User u = userDao.findById(Integer.parseInt(user.getId()));
        u.setName(user.getName());
        if (!file.isEmpty()){
            String filename = file.getOriginalFilename();
            String path = "F:\\springboot\\demo\\src\\main\\resources\\static\\files";
            try {
                file.transferTo(new File(path+File.separator+file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            String finalPath = "/files/" + filename;
            u.setUrl(finalPath);
        }
        u.setDepartment(department1);
        u.setAdministrator(user.getAdministrator());
        return "ok";
    }

}
